package com.ssyan.appointment.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssyan.appointment.cmn.listener.DictListener;
import com.ssyan.appointment.cmn.mapper.DictMapper;
import com.ssyan.appointment.cmn.service.DictService;
import com.ssyan.appointment.common.result.Result;
import com.ssyan.appointment.model.cmn.Dict;
import com.ssyan.appointment.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    //根据数据id查询子数据列表
    @Override
    @Cacheable(value = "dict", keyGenerator= "keyGenerator")
    public List<Dict> findChildData(Long id) {
        List<Dict> dictList = baseMapper.selectList(
                new QueryWrapper<Dict>().eq("parent_id", id));
        //向list集合中每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            dict.setHasChildren(this.hasChildren(dict.getId()));
        }
        return dictList;
    }

    //导出数据接口
    @Override
    public void exportDictData(HttpServletResponse response) {
        try {
            //下载信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系,防止文件名乱码
            String filename = URLEncoder.encode("数据字典", "UTF-8");
            //Content-disposition:操作方式为下载，attachment附件；filename：文件名
            response.setHeader("Content-disposition","attachment;filename="+filename+".xlsx");

            //查询数据库
            List<Dict> dictList = baseMapper.selectList(null);

            //DictEeVo对象用于将数据库返回的list集合封装为easyexcel的记录类型
            //类型转换：Dict --> DictEeVo (原生：遍历取值赋值 -> 封装API：BeanUtils.copyProperties）
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
            for (Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict,dictEeVo);
                dictVoList.add(dictEeVo);
            }
            //调用方法进行写操作
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("dict").doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //导入字典数据
    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper))
                        .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //根据dictcode和value查询
    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为空，直接根据value查询
        if (StringUtils.isEmpty(dictCode)) {
            //直接根据value定位唯一信息
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            return dict.getName();
        } else {
            //如果dictCode不为空，直接根据dictCode和value查询
            //业务逻辑，先根据dictCode获取id值（赋值为parent_id） - （id->parentId）和value值定位记录
            Dict codeDict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
            Dict dict = baseMapper.selectOne(
                    new QueryWrapper<Dict>()
                            .eq("parent_id", codeDict.getId())
                            .eq("value", value));
            return dict.getName();
        }
    }

    //根据dictCode获取下级列表
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictcode获取对应的id
        Dict codeDict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
        List<Dict> list = baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", codeDict.getId()));
        return list;
    }

    //判断id下面是否有子节点
    private boolean hasChildren(Long id){
        Integer count = baseMapper.selectCount(new QueryWrapper<Dict>().eq("parent_id", id));
        return count>0;
    }
}
